/**
 * Created by wfy on 2019/4/10.
 */
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const Goods = require('../models/goods');

mongoose.connect('mongodb://192.168.141.128:27017/dumall', {useNewUrlParser: true});

mongoose.connection.on('connected', () => {
    console.log('Mongodb connected success');
});

mongoose.connection.on('error', () => {
    console.log('Mongodb connected error');
});

mongoose.connection.on('disconnected', () => {
    console.log('Mongodb connected disconnected');
});

router.get('/', (req, res, next) => {

    let page = req.param('page') - 0;
    let pageSize = req.param('pageSize') - 0;
    let sort = req.param('sort') - 0;
    let pricelevel = req.param('pricelevel');
    let params = {};

    let skip = (page - 1) * pageSize;
    if (pricelevel.indexOf('-') > -1) {
        let prices = pricelevel.split('-');
        params = {
            productPrice: {
                $gt: prices[0] - 0,
                $lte: prices[1] - 0
            }
        }
    }

    let goodsModel = Goods.find(params).skip(skip).limit(pageSize);
    goodsModel.sort({productPrice: sort});
    goodsModel.exec((err, doc) => {
        if (err) {
            res.json({
                code: 1,
                message: ''
            })
        } else {
            res.json({
                code: 0,
                message: '请求成功',
                data: {
                    count: doc.length,
                    list: doc
                }
            })
        }
    })
});

module.exports = router;